'use strict';

export default class extends think.controller.base {

  /**
   *@description action请求验证用户token
   */
  async __before(action) {
    //登录、注册不验证token
    if (this.http.action === 'login' || this.http.action === 'register') {
      return;
    }
    var userInfo=await this.getUserInfo();
    if (!userInfo) {
      this.fail("TOKEN_INVALID")
    }
  }

  /*
   验证token
   */
  async checkHeaderToken(userToken){
    let tokenService = think.service("token");
    let tokenServiceInstance = new tokenService();
    let verifyTokenResult = await tokenServiceInstance.verifyToken(userToken);
    return verifyTokenResult === "fail"?false:true;
  }

  /*
    获取token
   */
  async getHeaderToken(id,name){
    //调用tokenservice中间件
    let tokenService = think.service("token");
    let tokenServiceInstance = new tokenService();
    //写入token
    let token = await tokenServiceInstance.createToken({
      userInfo: {
        id: id,
        name: name
      }
    });
    return token;
  }

  /*获取用户信息*/
  async getUserInfo(){
    var userInfo=await this.session("userInfo");
    return userInfo;
  }

  /*
   *设置基本信息
   */
  async setBaseInfo(targetObj,type){
    var userInfo=await this.getUserInfo();
    let timeStamp=new Date().getTime();
    targetObj.status=1;
    if(userInfo){
      let userFlag=userInfo.id;
      if(type=="add"){
        targetObj.creator=userFlag;
        targetObj.createDate=timeStamp;
        targetObj.lastModifyDate=timeStamp;
        targetObj.lastModifier=userFlag;
      }else if(type=="mdf"){
        targetObj.lastModifyDate=timeStamp;
        targetObj.lastModifier=userFlag;
      }
    }else{
      targetObj.createDate=timeStamp;
      targetObj.lastModifyDate=timeStamp;
    }
  }

  __call() {
      this.fail("NEED_LOGIN");
    }
    //用户信息
  userInfo() {
    return user;
  }

}
